﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Heaven.Engine.Concurrency
{
    /// <summary>
    /// Concurrent collection
    /// </summary>
    /// <typeparam name="T">Any type</typeparam>
    public class ConcurrentCollection<T> : GenericCollection<T>
    {
        #region Fields

        // Interthread locker
        ConcurrentLock locker = new ConcurrentLock();
        // Shadow copy
        DeferredCollection<T> shadow = new DeferredCollection<T>();

        #endregion

        #region Properties

        /// <summary>
        /// Shadow copy of collection
        /// </summary>
        public DeferredCollection<T> Shadow
        {
            get 
            {
                lock (shadow)
                {
                    shadow.Perform();
                }
                return shadow; 
            }
        }

        /// <summary>
        /// Locks this object
        /// </summary>
        /// <returns>Lock</returns>
        public ConcurrentLock Lock()
        {
            locker.Lock();
            return locker;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Adds an item
        /// </summary>
        /// <param name="item">An item</param>
        public override void Add(T item)
        {
            base.Add(item);
            shadow.Add(item);
        }

        /// <summary>
        /// Removes the given item
        /// </summary>
        /// <param name="item">An item</param>
        public override void Remove(T item)
        {
            base.Remove(item);
            shadow.Remove(item);
        }

        #endregion
    }
}
